<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>rtsp-to-flv</title>
  <style>
    html, body {
      width: 100%;
      height: 100%;
      padding: 0;
      margin: 0;
    }
    .container {
      padding: 20px 0;
    }
    .btn {
      margin: 10px;
    }
    .demo-video {
      width: 480px;
      height: 360px;
      margin: 10px;
    }
    .inp {
      width: 420px;
      padding: 4px 6px;
      font-size: 14px;
    }
  </style>
</head>
<body>
  <input id="urlInp" class="inp" type="text" value="rtsp://wowzaec2demo.streamlock.net/vod/mp4:BigBuckBunny_115k.mov">
  <button id="playBtn" class="btn">play</button>
  <button id="closeBtn" class="btn">close</button>
  <div class="container" id="rtsp-container"></div>

  <script src="../public/flv.min.js"></script>
  <script>
    (function() {
      if (!flvjs || !flvjs.isSupported()) {
        throw ReferenceError("flvjs is not supported!");
      }

      const container = document.getElementById("rtsp-container");
      const playBtn = document.getElementById("playBtn");
      const closeBtn = document.getElementById("closeBtn");
      const urlInp = document.getElementById("urlInp");

      let id = 0;
      let playerList = [];

      playBtn.addEventListener("click", play);
      closeBtn.addEventListener("click", close);
  
      function play () {
        let rtsp = urlInp.value;
        let video = document.createElement("video");
        video.setAttribute("class", "demo-video");
        video.setAttribute("data-index", id);
        video.setAttribute("controls", "controls");

        let player = flvjs.createPlayer({
          type: "flv",
          isLive: true,
          url: `ws://localhost:8888/rtsp/${id++}/?url=${rtsp}`,
        });
  
        player.attachMediaElement(video);
        playerList.push(player);
        container.appendChild(video);

        try {
          player.load();
          player.play();
        } catch (error) {
          throw Error(error);
        }
      }
  
      function close() {
        id = 0;

        playerList.forEach(e => {
          container.removeChild(e._mediaElement);
          e.detachMediaElement();
          e.destroy();
        });

        playerList.length = 0;
      }
    })();
  </script>
</body>
</html>